package com.fxu.framework.core.lock;

import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.codec.LZ4Codec;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * 配置Redis，使用Json格式化，LZ4压缩、Gzip压缩
 * @author fangxu
 * @version 1.0.0
 */
@Slf4j
@Component
public class RedissonConfig {

	@Value("${spring.redis.host:}")
	private String host;

	@Value("${spring.redis.port:}")
	private String port;

	@Value("${spring.redis.password:}")
	private String password;

	// 10.0.29.1:6379,10.0.29.2:6379
	@Value("${spring.redis.cluster.nodes:}")
	private String clusterNodes;

	@Value("${spring.redis.cluster.password:}")
	private String nodesPassword;

	@Bean
	public RedissonClient getRedisson() {
		Config config = new Config();
		config.setCodec(new LZ4Codec());

		String pswd = DesensitizedUtil.idCardNum(password, 3, 3);
		String nodesPswd = DesensitizedUtil.idCardNum(nodesPassword, 3, 3);
		log.debug("host={},port={},pswd={},nodes={},nodesPswd={}", host, port, pswd, clusterNodes, nodesPswd);
		if (!StrUtil.isEmpty(clusterNodes)) {
			String[] nodes = clusterNodes.split(",");
			for (int i = 0; i < nodes.length; i++) {
				nodes[i] = "redis://" + nodes[i];
			}
			log.debug("RedissonClient=>nodes={}", Arrays.toString(nodes));
			ClusterServersConfig serverConfig = config.useClusterServers()
					.setScanInterval(2000)
					.addNodeAddress(nodes)
					.setTimeout(2000)
					.setMasterConnectionPoolSize(200)
					.setSlaveConnectionPoolSize(200)
					.setMasterConnectionMinimumIdleSize(10)
					.setSlaveConnectionMinimumIdleSize(10);
			if (StringUtils.isNotBlank(nodesPassword)) {
				serverConfig.setPassword(nodesPassword);
			} else if (StringUtils.isNotBlank(password)) {
				serverConfig.setPassword(password);
			}
		} else if (!StrUtil.isEmpty(host) && !StrUtil.isEmpty(port)) {
			SingleServerConfig singleServerConfig = config.useSingleServer();
			singleServerConfig.setAddress("redis://" + host + ":" + port);
			if (!StrUtil.isEmpty(password)) {
				singleServerConfig.setPassword(password);
			}
			singleServerConfig.setConnectionPoolSize(200)
					.setConnectionMinimumIdleSize(10)
					.setTimeout(2000)
					.setConnectTimeout(2000)
					.setIdleConnectionTimeout(2000);
			//log.info("singleServerConfig={}", JSONUtil.toJsonStr(singleServerConfig));
		} else {
			log.error("host={},port={},pswd={},nodes={},nodesPswd={}", host, port, pswd, clusterNodes, nodesPswd);
		}
		return Redisson.create(config);
	}

}
